﻿using Aop.Api.Util;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using JumbotPay.API.Alipay.Mobile;
namespace JumbotPay.WebFile.Alipay_Mobile
{

    public partial class _return_url : JumbotPay.UI.BasicPage
    {
        public string account_alipay = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            account_alipay = q("account_no");
            //charset=UTF-8
            //out_trade_no=202009251119191554
            //method=alipay.trade.wap.pay.return
            //total_amount=1.00
            //sign=YPlZ%2Fm41zwdqW%2FJVnb%2FNyfMgMkPoaKQ6q%2F4WFYRUeNTEroMxhQsBvNoEU6lTUsfHk9l4Q5woSL%2BiplsOhtUOAJd1mSJYkD1RS9WgUKJ2m6n77Oti6OUYAYSuKTJ1g9J71BOvJxAt6X8eD6w1Y0lzSe%2BgcWwSJROXOPaCNBv6vQDgmBDj7glYry2mcrTS0kAfZz5g7jBKB7qXYdiKRbInTGZHRFrsplNAC2pSvbZjf2M0SwzhW%2By0kxlPoxu83q9Ab5mSJDtcEKem9JS1k%2BdJNVSax%2BJnKbzlUTt0ASpoOqCF18pA1LtM%2F56aPeO6WkVBpN9ftiF4cXT8x%2BFAD9ZOFw%3D%3D
            //trade_no=2020092522001472401435994692
            //auth_app_id=2018042202592122
            //version=1.0
            //app_id=2018042202592122
            //sign_type=RSA2
            //seller_id=2088821272338402
            //timestamp=2020-09-25+11%3A19%3A26
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            Dictionary<string, string> sArray = GetRequestGet();
            if (sArray.Count != 0)
            {
                Config conf = new Config(account_alipay);
                bool flag = AlipaySignature.RSACheckV1(sArray, conf.alipay_public_key, conf.charset, conf.sign_type, false);
                if (flag)
                {
                    string pay_order_id = Request.QueryString["trade_no"];              //支付宝交易号
                    string out_trade_no = Request.QueryString["out_trade_no"];	        //获取订单号
                    string total_amount = Request.QueryString["total_amount"];            //获取总金额
                    string seller_id = Request.QueryString["seller_id"];        //卖家商户号

                    object[] value = new JumbotPay.DAL.OrderDAL().GetOrderFields("alipay", out_trade_no, "", "appid");
                    string appid = value[0].ToString();



                    string _return_url = "";
                    string key = "";
                    doh.Reset();
                    doh.ConditionExpress = "appid=@appid";
                    doh.AddConditionParameter("@appid", appid);
                    object[] value2 = doh.GetFields("jpay_app", "return_url_mobile");
                    if (value2 != null)
                    {
                        _return_url = value2[0].ToString();
     
                        key = new JumbotPay.DAL.AppDAL().GetKey(appid);
                    }
                    else
                    {
                        Response.Write("app无效");
                        Response.End();
                    }




                    int pay_status = 1;//默认支付失败
                    if (new JumbotPay.DAL.OrderDAL().UpdateOrder("alipay", out_trade_no, pay_order_id,""))
                    {
                    }
                    pay_status = 0;

                    doh.Reset();
                    doh.ConditionExpress = "out_trade_no=@out_trade_no";
                    doh.AddConditionParameter("@out_trade_no", out_trade_no);
                    string order_id = doh.GetField("jpay_order", "order_id").ToString();//根据流水号反推业务订单号
                    string[] array1 = { "order_id=" + order_id, "pay_status=" + pay_status, "pay_order_id=" + out_trade_no };
                    string sign1 = JumbotPay.Utils.Strings.GetSign(array1, key);
                    JumbotPay.Utils.Logs.Debug("alipayM_return_verify_sign", "验证成功\r\n" + GetRequestParamStr(), false);
                    Response.Redirect(_return_url + "?" + JumbotPay.Utils.Strings.GetParaStr(array1, sign1));

                }
                else
                {
                    JumbotPay.Utils.Logs.Error("alipayM_return_verify_sign", "验证失败\r\n" + GetRequestParamStr(), false);
                    Response.Write(account_alipay+"同步验证失败");
                }
            }
        }

        public Dictionary<string, string> GetRequestGet()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll;
            //coll = Request.Form;
            coll = Request.QueryString;
            String[] requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                if (requestItem[i] != "account_no")
                    sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            }
            return sArray;

        }

        public string GetRequestParamStr()
        {
            string _str = "";
            Dictionary<string, string> sPara = GetRequestGet();
            foreach (KeyValuePair<string, string> temp in sPara)
            {
                _str += temp.Key + "=" + temp.Value + "&";
            }
            return _str;
        }
    }
}